package 每日一题OJ;

/**
 * @author shy_black
 * @date 2019/4/12 11:07
 * @Description:
 * 1.判断字符串首个字符是'+'还是'-'
 * 2.如果是+，先判断字符是否为+，然后逐个转换为数字
 * 3.输出时根据首个字符的符号判断输出为正数还是负数
 */
public class 把字符串转换成整数 {
    public int StrToInt(String str) {
        char[] arr = str.toCharArray();
        if (arr.length == 0)
            return 0;
        int result = 0;
        int singal = 0;
        if (arr[0] == '-')
            singal = 1;
        else
            singal = 0;
        for (int i = singal; i < arr.length; i++) {
            if (arr[i] == '+')
                continue;
            if (arr[i] >= '0' && arr[i] <= '9') {
                result = result * 10 + arr[i] - 48;
            } else {
                return 0;
            }
        }
        return singal == 0 ? result : result * -1;
    }
}